package db

import (
	"AQChain/models"
	"errors"
	"github.com/astaxie/beego/orm"
	"log"
)

var RequestMissingID = errors.New("request miss transfer.ID")
var RequestMissingCreateTx = errors.New("request miss transfer.OwnerTx")
var RequestMissingConfirmTx = errors.New("request miss transfer.BuyerTx")

func ReadTransfer(id string) *models.Transfer {
	t := &models.Transfer{
		ID: id,
	}
	err := orm.NewOrm().Read(t)
	if err != nil {
		if err != orm.ErrNoRows {
			log.Println(err)
		}
		return nil
	}
	return t
}

func ReadActiveTransfers(owner string) []*models.Transfer {
	var transfers []*models.Transfer
	_, err := orm.NewOrm().QueryTable(&models.Transfer{}).Filter("status", 0).Filter("buyer", "").Exclude("owner", owner).All(&transfers)
	if err != nil {
		log.Println(err)
		return nil
	}
	return transfers
}

func ReadOfferTransfers(buyer string) []*models.Transfer {
	var transfers []*models.Transfer
	_, err := orm.NewOrm().QueryTable(&models.Transfer{}).Filter("status", 1).Filter("buyer", buyer).All(&transfers)
	if err != nil {
		log.Println(err)
		return nil
	}
	return transfers
}

// 查询拥有者未确认Transfer
func ReadConfirmTransfers(owner string) []*models.Transfer {
	var transfers []*models.Transfer
	_, err := orm.NewOrm().QueryTable(&models.Transfer{}).Filter("status", 1).Filter("owner", owner).All(&transfers)
	if err != nil {
		log.Println(err)
		return nil
	}
	return transfers
}

// 查询购买者未确认Transfer
func ReadCompleteTransfers(buyer string) []*models.Transfer {
	var transfers []*models.Transfer
	_, err := orm.NewOrm().QueryTable(&models.Transfer{}).Filter("buyer", buyer).Filter("status", 2).All(&transfers)
	if err != nil {
		log.Println(err)
		return nil
	}
	return transfers
}

func ReadCompletedTransferByBuyer(o orm.Ormer, buyer string) []*models.Transfer {
	var transfers []*models.Transfer
	_, err := o.QueryTable(&models.Transfer{}).Filter("buyer", buyer).Filter("status", 3).OrderBy("timestamp").All(&transfers)
	if err != nil {
		log.Println(err)
		return nil
	}
	return transfers
}

func ReadTransfersByFileID(fileID string) []*models.Transfer {
	var transfers []*models.Transfer
	_, err := orm.NewOrm().QueryTable(&models.Transfer{}).Filter("file_id", fileID).All(&transfers)
	if err != nil {
		log.Println(err)
		return nil
	}
	return transfers
}

// 更新Request到确认状态
func UpdateTransferConfirm(orm orm.Ormer, transfer *models.Transfer) error {
	if len(transfer.ID) == 0 {
		return RequestMissingID
	}

	if len(transfer.BuyerTx) == 0 {
		return RequestMissingConfirmTx
	}

	transfer.Status = 1

	_, err := orm.Update(transfer, "status", "confirm_tx")
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

// 更新Request到确认状态
func UpdateTransferComplete(orm orm.Ormer, request *models.Transfer) error {

	request.Status = 2

	_, err := orm.Update(request, "status", "complete_tx")
	if err != nil {
		return err
	}
	return nil
}
